﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;

namespace Bundler
{
    public class BundleResponseHelper
    {
        private static readonly Regex Url = new Regex(@"url\(['""]?(?<url>[^)]+?)['""]?\)", RegexOptions.Singleline);

        public static void GetContent(BundleResponse response, bool replaceUrls)
        {

            var sb = new StringBuilder(string.Empty);

            foreach (var item in response.Bundle.Items)
            {
                string content = null;

                switch (item.Type)
                {
                    case BundleContentSourceType.VirtualPath:
                        var fileName = HttpHelper.MapPath(item.Value);
                        try
                        {
                            content = File.ReadAllText(fileName);
                        }
                        catch
                        {
                            continue;
                        }
                        break;
                    case BundleContentSourceType.RawContent:
                        content = item.Value;
                        break;
                }

                if (String.IsNullOrWhiteSpace(content))
                {
                    continue;
                }

                if (replaceUrls)
                {
                    var replacedUrls = new List<string>();

                    foreach (Match match in Url.Matches(content).Cast<Match>())
                    {
                        if (match.Groups.Count < 2)
                        {
                            continue;
                        }

                        var url = match.Groups[1].Value;

                        if (replacedUrls.Contains(url.ToLower()))
                        {
                            continue;
                        }

                        var imageVirutalPath = url;
                        var skip = url.StartsWith("data", StringComparison.OrdinalIgnoreCase);

                        if (skip)
                            continue;

                        if (url.StartsWith("~/"))
                        {
                            // do nothing
                        }
                        else if (url.StartsWith("/"))
                        {
                            imageVirutalPath = "~" + imageVirutalPath;
                        }
                        else
                        {
                            try
                            {
                                var virtualPath = response.Bundle.VirtualPath;
                                if (item.Type == BundleContentSourceType.VirtualPath)
                                {
                                    virtualPath = item.Value;
                                }
                                imageVirutalPath = VirtualPathUtility.Combine(virtualPath, url);
                            }
                            catch
                            {
                                skip = true;
                            }
                        }

                        if (skip)
                            continue;

                        var fixedRelativeImagePath = HttpHelper.MakeRelative(response.Bundle.VirtualPath, imageVirutalPath);
                        content = content.Replace(url, fixedRelativeImagePath);
                        replacedUrls.Add(url.ToLower());
                    }
                }

                sb.AppendLine(content);
            }

            response.Content = sb.ToString();
        }
    }
}
